package com.xiaoyu.client.ui.activity.main.mine.sign_and_help;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.mine.ParticularsBean;
import com.xiaoyu.client.model.seek.SeekBean;
import com.xiaoyu.client.model.seek.SeekParam;
import com.xiaoyu.client.model.seek.SeekReplyParam;
import com.xiaoyu.client.model.seek.UserSeekReplyBean;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.help.UserSeekInfoActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class MyHelpsFragment extends Fragment {

    private View mView;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.common_recycler_view)
    RecyclerView mRecyclerView;
    private List<SeekParam> mList = new ArrayList<>();
    private AllPowerfulAdapter mAdapter;
    private int page = 1;//当前页数
    private int totalPage;//总页数
    private String userId;//用户id

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            userId = bundle.getString(UserSeekInfoActivity.USER_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.common_recycler_view, container, false);
            //绑定fragment
            ButterKnife.bind(this, mView);
            initView();
        }

        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        mList.clear();
        getHelpInfo();
    }


    private void initView() {
        mSmartRefreshLayout.setOnRefreshListener(onRefreshListener);
        mSmartRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mSmartRefreshLayout.setNoMoreData(false);
        mRecyclerView.setBackgroundColor(Color.parseColor("#fffffe"));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(),
                LinearLayoutManager.VERTICAL);
        mRecyclerView.addItemDecoration(itemDecoration);

        setMyAdapter(mList);
    }

    private void setMyAdapter(final List<SeekParam> mList) {
        mAdapter = new AllPowerfulAdapter<SeekParam>(R.layout.item_help, mList) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, SeekParam param) {
                super.convert(baseViewHolder, param);
                CCircleImageView photoImg = baseViewHolder.getView(R.id.item_help_portrait);
                Glide.with(getActivity()).load(param.getUserphoto()).into(photoImg);
                baseViewHolder.setText(R.id.item_help_helper_name_txt, param.getNickname());
                ImageView stateImg = baseViewHolder.getView(R.id.item_help_solve_status_img);
                if (Integer.parseInt(param.getSeekstate()) == 0) {//0未解决，1已解决
                    stateImg.setImageResource(R.mipmap.icon_unsolved);
                } else {
                    stateImg.setImageResource(R.mipmap.icon_solved);
                }
                baseViewHolder.setText(R.id.item_help_publish_time_txt, param.getSeektime() + "发布");
                baseViewHolder.setText(R.id.item_help_content_txt, param.getSeektitle());
                baseViewHolder.setText(R.id.item_help_solved_num_txt, "以帮助 " + param.getSeeksum());
                baseViewHolder.setText(R.id.item_help_type_label_txt, param.getSeephelpname());
                baseViewHolder.setText(R.id.item_help_locate_txt, param.getSeekress());
                LinearLayout editLayout = baseViewHolder.getView(R.id.item_help_edit_layout);
                editLayout.setVisibility(View.GONE);

            }
        };
        mRecyclerView.setAdapter(mAdapter);
    }


    /**
     * 数据刷新
     */
    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            page = 1;
            mList.clear();
            mAdapter.notifyDataSetChanged();
            getHelpInfo();
            mSmartRefreshLayout.finishRefresh();
            mSmartRefreshLayout.setNoMoreData(false);
        }
    };


    /**
     * 加载更多
     */
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getHelpInfo();
                mSmartRefreshLayout.finishLoadMore();
                mSmartRefreshLayout.setNoMoreData(true);
            } else {
                ToastUtil.showToast(getActivity(), "已经没有更多数据！");
                mSmartRefreshLayout.finishLoadMore();
                mSmartRefreshLayout.setNoMoreData(false);
                mSmartRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    };

    /**
     * 获取我的求助信息
     */
    private void getHelpInfo() {
        NetworkManager.getSeekUserHelp(page, userId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseHelpSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void parseHelpSuc(String result) {
        if (page == 1) {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
        SeekBean bean = new Gson().fromJson(result, SeekBean.class);
        mList.addAll(bean.getSeekData().getList());
        mAdapter.notifyDataSetChanged();
        totalPage = Integer.parseInt(bean.getSeekData().getCount());
    }

}
